package com.qys.livesMall.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.framework.view.BaseQuery;
import com.qys.livesMall.shop.mapper.*;
import com.qys.livesMall.shop.modal.dto.UseDataPackageDTO;
import com.qys.livesMall.shop.modal.entity.*;
import com.qys.livesMall.shop.modal.vo.ShopTrafficSurplusVO;
import com.qys.livesMall.shop.modal.vo.SysShopDataConsumeVO;
import com.qys.livesMall.shop.service.SysShopDataConsumeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 店铺流量消耗表(SysShopDataConsume)表服务实现类
 *
 * @author makejava
 * @since 2023-07-04 10:12:54
 */
@Service("sysShopDataConsumeService")
public class SysShopDataConsumeServiceImpl extends ServiceImpl<SysShopDataConsumeMapper, SysShopDataConsume> implements SysShopDataConsumeService {

    @Resource
    private H2ShopBaseMapper shopBaseMapper;
    @Resource
    private SysPacketEffectMapper packetEffectMapper;
    @Resource
    private ShopDataStatisticsMapper shopDataStatisticsMapper;
    @Resource
    private ShopDataDetailMapper shopDataDetailMapper;

    @Override
    public IPage<SysShopDataConsumeVO> selectAll(BaseQuery dto) {

        Page<SysShopDataConsumeVO> page = new Page<>();
        page.setCurrent(dto.getPageNum());
        page.setCurrent(dto.getPageSize());

        dto.setPageNum((dto.getPageNum()-1) * dto.getPageSize());

        Long count = baseMapper.selectCount(Wrappers.query());
        if(count > 0){
            List<SysShopDataConsumeVO> list = baseMapper.getList(dto);
            page.setRecords(list);
            page.setTotal(count);
        }
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized void useDataPackage(UseDataPackageDTO dto) {
        String shopId = dto.getShopId();
        String packageEffectId = dto.getPackageEffectId();

        H2ShopBase shopBase = shopBaseMapper.selectById(shopId);
        if(Objects.isNull(shopBase)){
            throw new QysException(MessageUtils.message("shop.not.exist"));
        }

        SysPacketEffect sysPacketEffect = packetEffectMapper.selectById(packageEffectId);
        if(Objects.isNull(sysPacketEffect)){
            throw new QysException(MessageUtils.message("data.package.not.exist"));
        }

        //1.获取本次产生的消耗
        int consume = Integer.parseInt(sysPacketEffect.getConsume());


        //2.判断余额并更新店铺流量剩余表
        ShopDataStatistics statistics = shopDataStatisticsMapper.selectOne(Wrappers.<ShopDataStatistics>lambdaQuery().eq(ShopDataStatistics::getShopId, shopId));
        if(statistics == null){
            throw new QysException(MessageUtils.message("insufficient.flow.balance"));
        }
        boolean surplus = this.getSurplusByShopId(Long.valueOf(shopId), Long.valueOf(packageEffectId));
        if(!surplus){
            throw new QysException(MessageUtils.message("insufficient.flow.balance"));
        }

        ShopDataStatistics newDataStatistics = new ShopDataStatistics();
        newDataStatistics.setId(statistics.getId());
        newDataStatistics.setLastUseTime(LocalDateTime.now());
        if (sysPacketEffect.getId() == 4) {
            newDataStatistics.setInstation(statistics.getInstation() - consume);
        } else if (sysPacketEffect.getId() == 5) {
            newDataStatistics.setOutside(statistics.getOutside() - consume);
        } else if (sysPacketEffect.getId() == 6) {
            newDataStatistics.setOverseas(statistics.getOverseas() - consume);
        } else {
            newDataStatistics.setResidue(statistics.getResidue() - consume);
        }
        shopDataStatisticsMapper.updateById(newDataStatistics);

        //3.更新流量消耗表
        SysShopDataConsume oldData = baseMapper.selectOne(Wrappers.<SysShopDataConsume>lambdaQuery().eq(SysShopDataConsume::getShopId, shopId));

        SysShopDataConsume shopDataConsume = new SysShopDataConsume();
        shopDataConsume.setId(oldData.getId());
        if (sysPacketEffect.getId() == 1) {
            shopDataConsume.setHomePage(oldData.getHomePage() + consume);
            shopDataConsume.setResidue(oldData.getResidue() - consume);
        } else if (sysPacketEffect.getId() == 2) {
            shopDataConsume.setResidue(oldData.getResidue() - consume);
            shopDataConsume.setClassification(oldData.getClassification() + consume);
        } else if (sysPacketEffect.getId() == 3) {
            shopDataConsume.setResidue(oldData.getResidue() - consume);
            shopDataConsume.setSearch(oldData.getSearch() + consume);
        } else if(sysPacketEffect.getId() == 4) {
            shopDataConsume.setInstation(oldData.getInstation() + consume);
        } else if(sysPacketEffect.getId() == 5) {
            shopDataConsume.setOutside(oldData.getOutside() + consume);
        } else if(sysPacketEffect.getId() == 6) {
            shopDataConsume.setOverseas(oldData.getOverseas() + consume);
        }
        baseMapper.updateById(shopDataConsume);

        //4.保存流量交易明细
        ShopDataDetail dataDetail = new ShopDataDetail();
        dataDetail.setShopId(Long.valueOf(shopId));
        dataDetail.setTransactionType("2");
        dataDetail.setPacketId(Long.valueOf(packageEffectId));
        dataDetail.setVolume(consume);
        if (sysPacketEffect.getId() == 4) {
            dataDetail.setSurplus(statistics.getInstation() - consume);
        } else if (sysPacketEffect.getId() == 5) {
            dataDetail.setSurplus(statistics.getOutside() - consume);
        } else if (sysPacketEffect.getId() == 6) {
            dataDetail.setSurplus(statistics.getOverseas() - consume);
        } else {
            dataDetail.setSurplus(statistics.getResidue() - consume);
        }
        shopDataDetailMapper.insert(dataDetail);
    }

    @Override
    public boolean getSurplusByShopId(Long shopId, Long packetEffectId) {
        //店铺余量
        ShopDataStatistics statistics = shopDataStatisticsMapper.selectOne(Wrappers.<ShopDataStatistics>lambdaQuery().eq(ShopDataStatistics::getShopId, shopId));
        //推广效果
        SysPacketEffect sysPacketEffect = packetEffectMapper.selectById(packetEffectId);
        if(null == sysPacketEffect){
            throw new QysException("no PacketEffect");
        }
        int consume = Integer.parseInt(sysPacketEffect.getConsume());
        if(4 == packetEffectId){
            return (statistics.getInstation() == null ? 0 : statistics.getInstation()) >= consume;
        } else if(5 == packetEffectId){
            return (statistics.getOutside() == null ? 0 : statistics.getOutside()) >= consume;
        } else if(6 == packetEffectId){
            return (statistics.getOverseas() == null ? 0 : statistics.getOverseas()) >= consume;
        } else {
            return (statistics.getResidue() == null ? 0 : statistics.getResidue()) >= consume;
        }
    }

    @Override
    public ShopTrafficSurplusVO storeTrafficSurplus(String shopId) {
        ShopDataStatistics statistics = shopDataStatisticsMapper.selectOne(Wrappers.<ShopDataStatistics>lambdaQuery().eq(ShopDataStatistics::getShopId, shopId));
        if(statistics==null){
            return new ShopTrafficSurplusVO();
        }

        ShopTrafficSurplusVO shopTrafficSurplusVO = new ShopTrafficSurplusVO();
        shopTrafficSurplusVO.setResidue(statistics.getResidue());
        shopTrafficSurplusVO.setDeliveryHomepage(statistics.getInstation());
        shopTrafficSurplusVO.setOffStationPlatform(statistics.getOutside());
        shopTrafficSurplusVO.setOverseasPromotion(statistics.getOverseas());
        return shopTrafficSurplusVO;
    }
}

